﻿using System;
using System.Data;
using MySql.Data.MySqlClient;

namespace ConnectToDatabase
{
    public class ConnectDB:MarshalByRefObject
    {
        private string connectionString;
        private MySqlConnection connection = null;

        //public void setConnectionString(ref string _connectionString)
        //{
        //    _connectionString = "server=localhost;" + "database=dbgiaydep;" + "userid=root;" + "password=123456";
        //}

        public string setConnectionString()
        {
            connectionString = "server=localhost;" + "database=dbgiaydep;" + "userid=root;" + "password=123456";
            return connectionString;
        }

        //Query data using string query
        #region insert, update, delete
        public int QueryData(string cmdtext)
        {
            //setConnectionString();
            connection = new MySqlConnection(setConnectionString());
            MySqlCommand cmd = new MySqlCommand(cmdtext, connection);
            int kt = -1;

            try
            {
                //mo ket noi
                connection.Open();

                //thuc hien cau truy van thong qua MySqlCommand
                kt = cmd.ExecuteNonQuery();
                return kt;
            }
            catch (MySqlException err)
            {
                Console.WriteLine("Erron:" + err.ToString());
                return kt;
            }
            finally
            {
                //dong ket noi 
                if (connection != null)
                {
                    connection.Close();
                }
            }
        }
        #endregion

        #region Select

        //public DataSet SelectData(string cmdtext)
        //{
        //    setConnectionString();
        //    connection = new MySqlConnection(connectionString);
        //    DataSet ds = new DataSet();

        //    try
        //    {
        //        //tao ket noi
        //        connection.Open();

        //        //tao mot Adapter
        //        MySqlDataAdapter da = new MySqlDataAdapter(cmdtext, connection);
                
        //        //do du lieu vao dataset
        //        da.Fill(ds);


        //    }
        //    catch (Exception err)
        //    {
        //        Console.WriteLine("Erron:" + err.ToString());
        //    }
        //    finally
        //    {
        //        //dong ket noi
        //        if (connection != null)
        //        {
        //            connection.Close();
        //        }
        //    }
        //    return ds;
        //}

        #endregion

    }
}
